<?php namespace App\Http\Controllers\Api\Admin;

use App\Activity;
use App\Demands;
use App\Experts;
use App\Http\Controllers\Controller;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\News;
use App\PersonalAuth;
use App\Units;
use App\User;
use Illuminate\Http\Request;

class DataController extends Controller
{
    public function getAllCount(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $allUserCount     = User::count();
        $allUnitsCount    = Units::whereIsMemberUnit(1)->count();
        $allPersonalCount = PersonalAuth::whereIsAuth(1)->count();
        $allExpertsCount  = Experts::whereIsAuth(1)->count();
        $allDemandCount   = Demands::count();
        $allDemandActiveCount   = Demands::whereStatus(0)->count();
        $allNewsCount     = News::whereStatus(1)->count();
        $allActivityCount = Activity::whereStatus(1)->count();

        $result = [
            "user_count"=>$allUserCount,
            "unit_count"=>$allUnitsCount,
            "personal_count" => $allPersonalCount,
            "experts_count" => $allExpertsCount,
            "demand_count" => $allDemandCount,
            "demand_active_count" => $allDemandActiveCount,
            "news_count" => $allNewsCount,
            "activity_count" => $allActivityCount
        ];

        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$result]);
    }

    public function getUserWeekCount(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $theWeeks = ToolsManager::getWeeks();
        $dateArr = [];
        $userAllCountArr = [];
        $userEveryDayCountArr = [];
        foreach ($theWeeks as $theWeek){
            $userCount = User::where("created_at","<=",$theWeek)->count();
            $theDate = date("Y-m-d",strtotime($theWeek));

            $startTime = date("Y-m-d 00:00:00",strtotime($theWeek));
            $everyDayCount = User::whereBetween("created_at",[$startTime,$theWeek])->count();

            array_push($dateArr,$theDate);
            array_push($userAllCountArr,$userCount);
            array_push($userEveryDayCountArr,$everyDayCount);
        }

        $result = [
            "date" => $dateArr,
            "all_count"=>$userAllCountArr,
            "everyday_count" => $userEveryDayCountArr
        ];

        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$result]);
    }

    public function syncWechatVisitData(){
        $r = WechatLogin::getUserSmallAppVisitData("20200812","20200812");
        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$r]);
    }
}
